<template>
  <ElDrawer v-model="opened" :title="formType" size="40%" destroy-on-close>
    <ElSkeleton v-if="loading" animated :rows="10" />
    <ElForm v-else :model="form" :rules="rules" ref="formRef" status-icon :disabled="isView">
      <ElFormItem label="设备名称" :label-width="labelWidth" prop="deviceName">
        <ElInput v-model="form.deviceName" />
      </ElFormItem>
      <ElFormItem label="设备编码" :label-width="labelWidth" prop="deviceCode">
        <ElInput v-model="form.deviceCode" />
      </ElFormItem>
      <ElFormItem label="设备类型" :label-width="labelWidth" prop="deviceType">
        <ElInput v-model="form.deviceType" />
      </ElFormItem>
      <ElFormItem label="设备型号" :label-width="labelWidth" prop="deviceModel">
        <ElInput v-model="form.deviceModel" />
      </ElFormItem>
      <ElFormItem label="经度" :label-width="labelWidth" prop="longitude">
        <ElInput v-model="form.longitude" />
      </ElFormItem>
      <ElFormItem label="纬度" :label-width="labelWidth" prop="latitude">
        <ElInput v-model="form.latitude" />
      </ElFormItem>
      <ElFormItem label="监测参数数量" :label-width="labelWidth" prop="paramsCount">
        <ElInputNumber v-model="form.paramsCount" />
      </ElFormItem>
      <ElFormItem label="负责人" :label-width="labelWidth" prop="headName">
        <ElInput v-model="form.headName" />
      </ElFormItem>
      <ElFormItem label="建设时间" :label-width="labelWidth" prop="buildDate">
        <el-date-picker v-model="form.buildDate" value-format="YYYY-MM-DD" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton v-if="!isView" type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, unref, computed } from 'vue'
import { ElForm, ElFormItem, FormRules, FormInstance } from 'element-plus'
import {
  MonitoringStation,
  getMonitoringStationDetail,
  saveOrUpdateMonitoringStation,
  codeExist
} from '@/api/modules/tby/ecology/monitoringStation/monitoring-station'
import { FormType } from '@/enums'
import { validateLatitude, validateLongitude } from '@api/tby/common/common'

const labelWidth = 120
const opened = ref(false)
const loading = ref(true)
const formType = ref<FormType>()
const formRef = ref<FormInstance>()
const form = ref<Partial<MonitoringStation.Form>>({})

onMounted(async () => {
  console.log('进来了')
})

// 是否查看
const isView = computed(() => {
  return formType.value === FormType.VIEW
})

// 是否新增
const isAdd = computed(() => {
  return formType.value === FormType.ADD
})

const validateParamsCount = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  let str = value + ''
  if (str.length > 6) {
    callback(new Error('监测参数最大六位数字！'))
    return
  }
  const regExp = /^\d+(\.\d+)?$/
  if (value != '' && !regExp.test(value)) {
    callback(new Error('请输入有效的数字！'))
  } else {
    callback()
  }
}

const validateCode = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  codeExist(value, form.value?.id).then(resp => {
    if (resp.data) {
      callback(new Error('设备编码已存在'))
    } else {
      callback()
    }
  })
}

const rules = reactive<FormRules>({
  deviceName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { max: 20, message: '山峰名称最大20个字符', trigger: 'blur' }
  ],
  deviceCode: [
    { required: true, message: '请输入设备编码', trigger: 'blur' },
    { max: 255, message: '设备编码最大255个字符', trigger: 'blur' },
    { validator: validateCode, trigger: 'blur' }
  ],
  deviceType: [
    { required: true, message: '请输入设备型号', trigger: 'blur' },
    { max: 255, message: '设备型号最大255个字符', trigger: 'blur' }
  ],
  deviceModel: [
    { required: true, message: '请输入设备型号', trigger: 'blur' },
    { max: 20, message: '设备型号最大20个字符', trigger: 'blur' }
  ],
  longitude: [
    { required: true, message: '请输入经度', trigger: 'blur' },
    { max: 32, message: '经度最大32个字符', trigger: 'blur' },
    { validator: validateLongitude, trigger: 'blur' }
  ],
  latitude: [
    { required: true, message: '请输入纬度', trigger: 'blur' },
    { max: 32, message: '纬度最大32个字符', trigger: 'blur' },
    { validator: validateLatitude, trigger: 'blur' }
  ],
  paramsCount: [
    { required: true, message: '请输入监测参数数量', trigger: 'blur' },
    { validator: validateParamsCount, trigger: 'blur' }
  ]
})

const open = async (type: FormType, id?: number) => {
  form.value = {}
  formType.value = type
  opened.value = true
  if (isAdd.value) {
    loading.value = false
  } else {
    try {
      const { data } = await getMonitoringStationDetail(id!)
      loading.value = false
      form.value = data
      form.value.buildDate = form.value.buildDateFormat
    } finally {
      loading.value = false
    }
  }
  formRef.value?.clearValidate()
}

function close() {
  loading.value = true
  opened.value = false
  form.value = {}
}

const onSaveClicked = () => {
  if (!formRef.value) return
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    const formData = { ...unref(form) }
    saveOrUpdateMonitoringStation(formData).then(response => {
      console.log(response)
      sendSuccess()
      close()
    })
  })
}

const onCancelClicked = () => {
  close()
}

defineExpose({
  open,
  close
})

const emit = defineEmits(['success'])

function sendSuccess() {
  emit('success')
}
</script>
